﻿using K4os.Compression.LZ4;
using NetMQ;
using NetMQ.Sockets;
using System.Text;

namespace ZeroMQCommon
{

    // -------------------------
    // ZeroMQ Sender Example
    // -------------------------
    public static class ZmqImageSender
    {
        public static void SendImage(byte[] rawData, string imageId, string address, int chunkSize = 1024 * 1024)
        {
            byte[] compressed = LZ4Pickler.Pickle(rawData);
            int totalChunks = (compressed.Length + chunkSize - 1) / chunkSize;

            using var socket = new PushSocket();
            socket.Connect(address);

            for (int i = 0; i < totalChunks; i++)
            {
                int start = i * chunkSize;
                int length = Math.Min(chunkSize, compressed.Length - start);
                var chunk = new byte[length + 64];

                Buffer.BlockCopy(compressed, start, chunk, 64, length);
                var meta = Encoding.UTF8.GetBytes($"{imageId}:{i}:{totalChunks}");
                Buffer.BlockCopy(meta, 0, chunk, 0, meta.Length);

                socket.SendFrame(chunk);
            }
        }
    }
}
